import baostock as bs
import pandas as pd
from decimal import Decimal
import math
import numpy as np
import datetime
import matplotlib.pyplot as plt
class GetStockDat():





    def GetStockDatApi(self,code,N1,N2,N3,date,bs):
        #bs.login(user_id='anonymous', password='123456')
        df = bs.query_history_k_data_plus(code,
                                          "date,code,open,,low,close",
                                          start_date=date, end_date='%s-%s-%s' % (
                datetime.datetime.now().year, datetime.datetime.now().month, datetime.datetime.now().day),
                                          frequency="m",
                                          adjustflag="2")
        data_list = []
        poorList=[]
        while (df.error_code == '0') & df.next():
            data=df.get_row_data()
            poorList.append(data[0])
            data_list.append(data)
        stockdata = pd.DataFrame(data_list, columns=df.fields)
        stockdata = stockdata.astype({'high': 'float', 'open': 'float', 'close': 'float', 'low': 'float'})
        df_close = stockdata.close / stockdata.close[0]  # 计算净值
        wave = []
        wave_two = []
        wave_three = []
        for i in range(0, len(stockdata.index)):  # 计算20天的波动率
            if i>20:
               wave.append(np.std(np.log(df_close[i - 20:i] / df_close[i - 20:i].shift(-1))) * np.sqrt(252) * 100)
            else :
               wave.append(0)
        stockdata['wave'] = pd.DataFrame({'wave': wave},index=(stockdata.index))
        for i in range(0, len(stockdata.index)):  # 计算20天的波动率
            if i > 50:
                wave_two.append(np.std(np.log(df_close[i - 50:i] / df_close[i - 50:i].shift(-1))) * np.sqrt(252) * 100)
            else:
                wave_two.append(0)
        stockdata['wave_two'] = pd.DataFrame({'wave_two': wave_two}, index=(stockdata.index))
        for i in range(0, len(stockdata.index)):  # 计算20天的波动率
            if i > 70:
                wave_three.append(np.std(np.log(df_close[i - 70:i] / df_close[i - 70:i].shift(-1))) * np.sqrt(252) * 100)
            else:
                wave_three.append(0)
        stockdata['wave_three'] = pd.DataFrame({'wave_three': wave_three}, index=(stockdata.index))

        expan_h = stockdata.close.expanding().max()
        stockdata['N_High'] = stockdata.high.rolling(window=5).max()  # 计算最近N1个交易日最高价
        stockdata['N_High'].fillna(value=expan_h, inplace=True)  # 目前出现过的最大值填充前N1个nan
        stockdata['N_Low'] = stockdata.low.rolling(window=200).min()  # 计算最近N2个交易日最低价
        b=False
        for i in range(0, len(stockdata.index)):
            if i >20 and i == len(stockdata.index)-1 :
                high = stockdata['high']
                close = stockdata['close']
                open = stockdata['open']
                wave=stockdata['wave']
                wave_two = stockdata['wave_two']
                wave_three = stockdata['wave_three']
                average_h = (close[i-1] + close[i]) / 2
                if  (( average_h>close[i] and average_h>open[i] and average_h<high[i] )   )  :
                    if    wave[i]<150 and  wave[i] < wave_two[i] and wave_two[i]<wave_three[i] :
                        #print(stockdata.date)
                        b = True

        if b:
            print(code)
            '''try:
                m = stockdata['close']
                plt.plot(m)
                va = "参数：code:'%s'" % (code)
                plt.title(va)
                plt.show()
            except Exception as err:
                print("Finished with error: ", err)'''


            #return stockdata